package buddhi.main.MyTour;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

/**
 * @author Buddhiprabha
 *
 */

public class MapRouteActivity extends MapActivity {

	public List<String> longts = new ArrayList<String>();
	public List<String> latituds = new ArrayList<String>();
        LinearLayout linearLayout;
        MapView mapView;
        private Road mRoad;
        String temp[];
    	String cord[];
    	String url;
    	double fromLat, fromLon, toLat, toLon;
    	List<Overlay> listOfOverlays;
    	OverlayItem overlayitem;
    	List<Overlay> mapOverlays;
        
        InputStream is;

        @Override
        public void onCreate(Bundle savedInstanceState) {
        	
        	ArrayList<String> list = new ArrayList<String>();
            list = (ArrayList<String>)getIntent().getExtras().getStringArrayList("selected");
                       
        	String line;
                super.onCreate(savedInstanceState);
                setContentView(R.layout.maprouteactivity);
                mapView = (MapView) findViewById(R.id.mapview);
                mapView.setBuiltInZoomControls(true);
                mapView.setSatellite(true);
                listOfOverlays = mapView.getOverlays();
                mapOverlays = mapView.getOverlays();
                
                
                InputStream inputStream = getResources().openRawResource(R.raw.positions);
                BufferedReader read = new BufferedReader(new InputStreamReader(inputStream));
                
                try {
        			line = read.readLine();
        			
        			while (line!=null) {
        				temp = line.split("\\=");
        				if(list.contains(temp[0])){
        				cord = ((String) temp[1]).split("\\,");
        				longts.add(cord[0]);
        				latituds.add(cord[1]);
        	        }
        				line = read.readLine();}
        			inputStream.close();
        		} catch (IOException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
                

                Thread timer = new Thread() {
                        @Override
                        public void run() {
                        	
                                for(int i = 0; i <longts.size()-1;i++){
                                	try{
                    					sleep(3000);
                    				}catch(InterruptedException e){
                    					e.printStackTrace();
                    				}
                                	url = RoadProvider.getUrl(Double.parseDouble(longts.get(i)), Double.parseDouble(latituds.get(i)), 
                                			Double.parseDouble(longts.get(i+1)), Double.parseDouble(latituds.get(i+1)));
                                	is = getConnection(url);
                                	mRoad = RoadProvider.getRoute(is);
                                	MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
                                	listOfOverlays.add(mapOverlay);
                                	mHandler.sendEmptyMessage(0);
                                }
                                
                        }
                };
                timer.start();
        }

        Handler mHandler = new Handler() {
                public void handleMessage(android.os.Message msg) {
                        TextView textView = (TextView) findViewById(R.id.description);
                        textView.append(mRoad.mName + " " + mRoad.mDescription+". ");
                        mapView.invalidate();
                };
        };

        private InputStream getConnection(String url) {
                InputStream is = null;
                try {
                        URLConnection conn = new URL(url).openConnection();
                        is = conn.getInputStream();
                } catch (MalformedURLException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
                return is;
        }

        @Override
        protected boolean isRouteDisplayed() {
                return false;
        }
}

class MapOverlay extends com.google.android.maps.Overlay {
        Road mRoad;
        ArrayList<GeoPoint> mPoints;

        public MapOverlay(Road road, MapView mv) {
                mRoad = road;
                if (road.mRoute.length > 0) {
                        mPoints = new ArrayList<GeoPoint>();
                        for (int i = 0; i < road.mRoute.length; i++) {
                                mPoints.add(new GeoPoint((int) (road.mRoute[i][1] * 1000000),
                                                (int) (road.mRoute[i][0] * 1000000)));
                        }
                        MapController mapController = mv.getController();
                        String coordinates[] = {"7.87305", "80.77180"};
                        double lat = Double.parseDouble(coordinates[0]);
                        double lng = Double.parseDouble(coordinates[1]);
                        GeoPoint p = new GeoPoint(
                        (int) (lat * 1E6),
                        (int) (lng * 1E6));
                        mapController.animateTo(p);
                        mapController.setZoom(9);
                }
        }

        @Override
        public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {
                super.draw(canvas, mv, shadow);
                drawPath(mv, canvas);
                return true;
        }

        public void drawPath(MapView mv, Canvas canvas) {
        	
                int x1 = -1, y1 = -1, x2 = -1, y2 = -1;
                Paint paint = new Paint();
                paint.setColor(Color.RED);
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(3);
                for (int i = 0; i < mPoints.size(); i++) {
                        Point point = new Point();
                        mv.getProjection().toPixels(mPoints.get(i), point);
                        x2 = point.x;
                        y2 = point.y;
                        if (i > 0) {
                                canvas.drawLine(x1, y1, x2, y2, paint);
                        }
                        x1 = x2;
                        y1 = y2;
                }
        }
}